import sys
import os
import shutil
import time
import json
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                           QHBoxLayout, QTreeWidget, QTreeWidgetItem, QPushButton,
                           QComboBox, QProgressBar, QFileDialog, QLabel, QStatusBar,
                           QGroupBox, QTextEdit, QMessageBox, QDialog, QLineEdit, QDialogButtonBox,
                           QFormLayout, QCheckBox, QSpinBox, QProgressDialog)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize, QSettings, QTimer, QRect
from PyQt6.QtGui import (QFont, QPalette, QColor, QIcon, QPainter, QPen, QPixmap,
                      QKeySequence, QShortcut)
from file_processor import FileProcessor

# 定义样式表
STYLE_SHEET = """
QMainWindow {
    background-color: #f5f6fa;
}

QTreeWidget {
    background-color: #ffffff;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    padding: 5px;
    font-size: 14px;
}

QTreeWidget::item {
    height: 30px;
    color: #2c3e50;
    padding: 5px;
    border-radius: 4px;
}

QTreeWidget::item:hover {
    background-color: #f0f0f0;
}

QTreeWidget::item:selected {
    background-color: #3498db;
    color: white;
}

QTreeWidget::branch {
    background-color: transparent;
}

QTreeWidget::branch:has-siblings:!adjoins-item {
    border-image: url(none.png);
}

QTreeWidget::branch:has-siblings:adjoins-item {
    border-image: url(none.png);
}

QTreeWidget::branch:!has-children:!has-siblings:adjoins-item {
    border-image: url(none.png);
}

QTreeWidget::branch:has-children:!has-siblings:closed,
QTreeWidget::branch:closed:has-children:has-siblings {
    border-image: none;
    image: url(none.png);
}

QTreeWidget::branch:open:has-children:!has-siblings,
QTreeWidget::branch:open:has-children:has-siblings {
    border-image: none;
    image: url(none.png);
}

QPushButton {
    background-color: #3498db;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 4px;
    font-weight: bold;
}

QPushButton:hover {
    background-color: #2980b9;
}

QPushButton:disabled {
    background-color: #bdc3c7;
}

QGroupBox {
    background-color: white;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    margin-top: 12px;
    padding: 15px;
}

QGroupBox::title {
    background-color: transparent;
    padding: 5px;
    subcontrol-origin: margin;
    subcontrol-position: top left;
    color: #2c3e50;
    font-weight: bold;
}

QTextEdit {
    background-color: #ffffff;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    padding: 5px;
}

QProgressBar {
    border: none;
    border-radius: 4px;
    text-align: center;
    background-color: #ecf0f1;
    height: 20px;
}

QProgressBar::chunk {
    background-color: #2ecc71;
    border-radius: 4px;
}

QLabel {
    color: #2c3e50;
}

QComboBox {
    border: 1px solid #e1e1e1;
    border-radius: 4px;
    padding: 5px;
    background-color: white;
    min-width: 6em;
}

QComboBox::drop-down {
    border: none;
    width: 20px;
}

QComboBox::down-arrow {
    border: none;
    background: #3498db;
    width: 16px;
    height: 16px;
    border-radius: 2px;
}

QComboBox::down-arrow:hover {
    background: #2980b9;
}

QStatusBar {
    background-color: #ffffff;
    color: #2c3e50;
    padding: 5px;
    font-weight: bold;
}

/* 添加滚动条样式 */
QScrollBar:vertical {
    border: none;
    background: #f1f1f1;
    width: 10px;
    border-radius: 5px;
}

QScrollBar::handle:vertical {
    background: #c1c1c1;
    border-radius: 5px;
    min-height: 20px;
}

QScrollBar::handle:vertical:hover {
    background: #a1a1a1;
}

QScrollBar::add-line:vertical,
QScrollBar::sub-line:vertical {
    height: 0px;
}

QScrollBar::add-page:vertical,
QScrollBar::sub-page:vertical {
    background: none;
}

/* 添加工具提示样式 */
QToolTip {
    background-color: #2c3e50;
    color: white;
    border: none;
    padding: 5px;
    border-radius: 3px;
}
"""

class ConversionThread(QThread):
    progress_updated = pyqtSignal(int)
    conversion_finished = pyqtSignal()
    error_occurred = pyqtSignal(str)
    
    def __init__(self, processor, input_path, output_path, operation):
        super().__init__()
        self.processor = processor
        self.input_path = input_path
        self.output_path = output_path
        self.operation = operation
        
    def run(self):
        try:
            # 设置进度回调
            self.processor.set_progress_callback(lambda value: self.progress_updated.emit(value))
            
            # 根据操作类型调用相应的转换方法
            if self.operation == "去水印":
                if self.input_path.endswith('.pdf'):
                    self.processor.remove_watermark_pdf(self.input_path, self.output_path)
                elif self.input_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
                    self.processor.remove_watermark_image(self.input_path, self.output_path)
            elif self.operation == "转图片":
                self.processor.pdf_to_image(self.input_path, self.output_path)
            elif self.operation == "转文本":
                if self.input_path.endswith('.pdf'):
                    self.processor.pdf_to_text(self.input_path, self.output_path)
                elif self.input_path.lower().endswith(('.png', '.jpg', '.jpeg')):
                    self.processor.image_to_text(self.input_path, self.output_path)
            elif self.operation == "转表格":
                self.processor.pdf_to_table(self.input_path, self.output_path)
            elif self.operation == "转PPT":
                self.processor.pdf_to_ppt(self.input_path, self.output_path)
            elif self.operation == "转Word":
                self.processor.pdf_to_word(self.input_path, self.output_path)
            elif self.operation == "转PDF":
                if self.input_path.endswith(('.docx', '.doc')):
                    self.processor.word_to_pdf(self.input_path, self.output_path)
                elif self.input_path.endswith(('.xlsx', '.xls')):
                    self.processor.excel_to_pdf(self.input_path, self.output_path)
                elif self.input_path.endswith(('.pptx', '.ppt')):
                    self.processor.ppt_to_pdf(self.input_path, self.output_path)
                    
            self.conversion_finished.emit()
        except Exception as e:
            self.error_occurred.emit(str(e))

class FileConverterApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("文件转换器")
        self.setGeometry(100, 100, 1000, 700)
        self.setStyleSheet(STYLE_SHEET)
        
        # 添加快捷键
        self.screenshot_shortcut = QShortcut(QKeySequence("Alt+W"), self)
        self.screenshot_shortcut.activated.connect(self.take_screenshot)
        
        # 初始化截图预览
        self.screenshot_preview = QLabel()
        self.screenshot_preview.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.screenshot_preview.setMinimumSize(400, 300)
        self.screenshot_preview.setStyleSheet("""
            QLabel {
                border: 2px solid #ddd;
                border-radius: 4px;
                background-color: #f9f9f9;
                margin: 10px;
            }
        """)
        
        # 加载配置
        self.load_settings()
        
        # 设置应用字体
        app_font = QFont("Microsoft YaHei UI", 9)
        QApplication.setFont(app_font)
        
        # 定义版本号
        self.version = "1.0.0"
        
        # 定义支持的文件类型
        self.supported_formats = {
            "PDF处理": [".pdf"],
            "图片处理": [".png", ".jpg", ".jpeg", ".bmp", ".gif"],
            "Word处理": [".docx", ".doc"],
            "Excel处理": [".xlsx", ".xls"],
            "PPT处理": [".pptx", ".ppt"]
        }
        
        # 定义每个处理类型支持的功能
        self.supported_operations = {
            "PDF处理": ["去水印", "转图片", "转文本", "转表格", "转PPT", "转Word"],
            "图片处理": ["去水印", "转PDF", "转文本", "转表格", "转PPT", "转Word", "转Excel"],
            "Word处理": ["去水印", "转PDF", "转图片", "转文本", "转表格", "转PPT"],
            "Excel处理": ["去水印", "转PDF", "转图片", "转文本", "转PPT", "转Word"],
            "PPT处理": ["去水印", "转PDF", "转图片", "转文本"]
        }
        
        # 创建文件处理器
        self.processor = FileProcessor()
        
        # 初始化OCR客户端
        if self.kimi_api_key:
            try:
                self.processor.init_kimi_client()
            except Exception as e:
                QMessageBox.warning(self, "警告", f"初始化OCR客户端失败: {str(e)}")
        
        # 创建中央部件和主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.main_layout = QHBoxLayout(central_widget)
        self.main_layout.setSpacing(20)
        self.main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 添加侧边栏
        self.sidebar = self.setup_sidebar()
        self.main_layout.addWidget(self.sidebar)
        
        # 创建右侧功能区容器
        self.function_container = QWidget()
        self.function_layout = QVBoxLayout(self.function_container)
        self.function_layout.setSpacing(15)
        
        # 创建截图功能区容器
        self.screenshot_container = QWidget()
        self.screenshot_layout = QVBoxLayout(self.screenshot_container)
        self.screenshot_layout.setContentsMargins(0, 0, 0, 0)
        self.screenshot_container.hide()  # 初始时隐藏截图容器
        
        # 右侧面板
        self.right_panel = QWidget()
        right_layout = QVBoxLayout(self.right_panel)
        right_layout.setSpacing(15)
        
        # 文件信息显示区域
        file_info_group = QGroupBox("文件信息")
        file_info_layout = QVBoxLayout()
        file_info_layout.setSpacing(10)
        
        self.file_path_label = QLabel("未选择文件")
        self.file_info_text = QTextEdit()
        self.file_info_text.setReadOnly(True)
        self.file_info_text.setMaximumHeight(100)
        
        file_info_layout.addWidget(QLabel("当前文件:"))
        file_info_layout.addWidget(self.file_path_label)
        file_info_layout.addWidget(QLabel("文件信息:"))
        file_info_layout.addWidget(self.file_info_text)
        file_info_group.setLayout(file_info_layout)
        
        # 转换结果区域
        result_group = QGroupBox("转换结果")
        result_layout = QVBoxLayout()
        self.result_label = QLabel("尚未开始转换")
        self.result_label.setWordWrap(True)
        self.result_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        self.result_label.setOpenExternalLinks(True)
        result_layout.addWidget(self.result_label)
        result_group.setLayout(result_layout)
        
        # 转换操作区域
        operation_area = QGroupBox("转换操作")
        operation_area_layout = QVBoxLayout()
        operation_area_layout.setSpacing(15)
        
        # 转换选项
        conversion_layout = QHBoxLayout()
        conversion_layout.addWidget(QLabel("转换类型:"))
        self.conversion_combo = QComboBox()
        self.conversion_combo.setMinimumHeight(30)
        conversion_layout.addWidget(self.conversion_combo)
        operation_area_layout.addLayout(conversion_layout)
        
        # 转换和保存按钮
        buttons_layout = QHBoxLayout()
        
        # 转换按钮
        self.convert_btn = QPushButton("开始转换")
        self.convert_btn.setMinimumHeight(35)
        self.convert_btn.setStyleSheet("""
            QPushButton {
                background-color: #27ae60;
            }
            QPushButton:hover {
                background-color: #2ecc71;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
            }
        """)
        buttons_layout.addWidget(self.convert_btn)
        
        operation_area_layout.addLayout(buttons_layout)
        
        # 进度条
        progress_layout = QVBoxLayout()
        progress_layout.addWidget(QLabel("转换进度:"))
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setTextVisible(True)
        progress_layout.addWidget(self.progress_bar)
        operation_area_layout.addLayout(progress_layout)
        
        operation_area.setLayout(operation_area_layout)
        
        # 添加所有组件到右侧面板
        right_layout.addWidget(file_info_group)
        right_layout.addWidget(result_group)
        right_layout.addWidget(operation_area)
        right_layout.addStretch()
        
        # 将右侧面板添加到功能区容器
        self.function_layout.addWidget(self.right_panel)
        
        # 将功能区容器和截图容器添加到主布局
        self.main_layout.addWidget(self.function_container, stretch=2)
        self.main_layout.addWidget(self.screenshot_container, stretch=2)
        
        # 创建状态栏
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar.showMessage("就绪")
        
        # 连接信号
        self.convert_btn.clicked.connect(self.start_conversion)
        self.result_label.linkActivated.connect(self.open_result_folder)
        
        # 初始化变量
        self.current_file_type = None
        self.current_operation = None
        self.current_file_path = None
        self.converted_file_path = None
        self.current_page = None
        
    def setup_sidebar(self):
        """设置侧边栏"""
        sidebar = QWidget()
        sidebar.setFixedWidth(200)
        sidebar.setStyleSheet("""
            QWidget {
                background-color: #f0f0f0;
                border-right: 1px solid #ddd;
            }
            QPushButton {
                text-align: left;
                padding: 10px;
                border: none;
                border-radius: 4px;
                margin: 5px;
                background-color: white;
                color: #333;
                font-size: 14px;
                font-weight: normal;
            }
            QPushButton:hover {
                background-color: #e0e0e0;
                color: #000;
            }
            QPushButton:pressed {
                background-color: #d0d0d0;
            }
            QPushButton:checked {
                background-color: #2196F3;
                color: white;
            }
            QLabel {
                padding: 10px;
                color: #666;
            }
        """)
        
        layout = QVBoxLayout()
        layout.setSpacing(2)
        layout.setContentsMargins(10, 10, 10, 10)
        
        # 功能菜单标题
        menu_title = QLabel("功能菜单")
        menu_title.setStyleSheet("""
            font-size: 16px;
            font-weight: bold;
            color: #2c3e50;
            padding: 10px 5px;
            border-bottom: 1px solid #ddd;
            margin-bottom: 5px;
        """)
        layout.addWidget(menu_title)
        
        # 添加功能按钮
        self.function_buttons = []
        button_colors = {
            "PDF处理": ("#F44336", "#D32F2F"),  # 红色
            "图片处理": ("#4CAF50", "#388E3C"),  # 绿色
            "Word处理": ("#2196F3", "#1976D2"),  # 蓝色
            "Excel处理": ("#FF9800", "#F57C00"),  # 橙色
            "PPT处理": ("#9C27B0", "#7B1FA2")   # 紫色
        }
        
        for category in self.supported_formats.keys():
            btn = QPushButton(category)
            btn.setMinimumHeight(40)
            btn.setCheckable(True)
            
            # 设置按钮颜色
            if category in button_colors:
                normal_color, hover_color = button_colors[category]
                btn.setStyleSheet(f"""
                    QPushButton {{
                        text-align: left;
                        padding: 10px;
                        border: none;
                        border-radius: 4px;
                        margin: 5px;
                        background-color: {normal_color};
                        color: white;
                        font-size: 14px;
                    }}
                    QPushButton:hover {{
                        background-color: {hover_color};
                    }}
                    QPushButton:checked {{
                        background-color: {hover_color};
                        border: 2px solid white;
                    }}
                """)
            
            btn.clicked.connect(lambda checked, c=category: self.handle_function_click(c))
            self.function_buttons.append(btn)
            layout.addWidget(btn)
            
        # 添加分隔线
        separator = QLabel("")
        separator.setStyleSheet("border-bottom: 1px solid #ddd; margin: 5px 0;")
        layout.addWidget(separator)
            
        # 添加截图按钮
        self.screenshot_btn = QPushButton("截图")
        self.screenshot_btn.setMinimumHeight(40)
        self.screenshot_btn.setCheckable(True)
        self.screenshot_btn.setStyleSheet("""
            QPushButton {
                text-align: left;
                padding: 10px;
                border: none;
                border-radius: 4px;
                margin: 5px;
                background-color: #00BCD4;
                color: white;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0097A7;
            }
            QPushButton:checked {
                background-color: #0097A7;
                border: 2px solid white;
            }
        """)
        self.screenshot_btn.clicked.connect(self.handle_screenshot_click)
        layout.addWidget(self.screenshot_btn)
        
        # 添加设置按钮
        settings_btn = QPushButton("设置")
        settings_btn.setMinimumHeight(40)
        settings_btn.setCheckable(True)
        settings_btn.setStyleSheet("""
            QPushButton {
                text-align: left;
                padding: 10px;
                border: none;
                border-radius: 4px;
                margin: 5px;
                background-color: #607D8B;
                color: white;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #455A64;
            }
            QPushButton:checked {
                background-color: #455A64;
                border: 2px solid white;
            }
        """)
        settings_btn.clicked.connect(self.show_settings)
        layout.addWidget(settings_btn)
        
        # 添加版本信息
        version_label = QLabel(f"版本: {self.version}")
        version_label.setStyleSheet("color: #666; font-size: 12px;")
        version_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 添加版权信息
        copyright_label = QLabel("© 2024 File Converter")
        copyright_label.setStyleSheet("color: #666; font-size: 12px;")
        copyright_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 添加弹性空间
        layout.addStretch()
        
        # 添加底部信息
        bottom_info = QWidget()
        bottom_layout = QVBoxLayout()
        bottom_layout.addWidget(version_label)
        bottom_layout.addWidget(copyright_label)
        bottom_info.setLayout(bottom_layout)
        layout.addWidget(bottom_info)
        
        sidebar.setLayout(layout)
        return sidebar

    def load_settings(self):
        """加载设置"""
        settings = QSettings('FileConverter', 'Settings')
        # 加载临时目录设置
        self.temp_dir = settings.value('temp_dir', 
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'temp'))
        os.makedirs(self.temp_dir, exist_ok=True)
        
        # 加载KIMI API密钥
        self.kimi_api_key = settings.value('kimi_api_key', '')
        
    def show_settings(self):
        """显示设置对话框"""
        dialog = SettingsDialog(self.temp_dir, self.processor)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            self.temp_dir = dialog.get_temp_dir()
            self.kimi_api_key = dialog.get_api_key()
            
            # 保存设置
            settings = QSettings('FileConverter', 'Settings')
            settings.setValue('temp_dir', self.temp_dir)
            settings.setValue('kimi_api_key', self.kimi_api_key)
            
            # 重新初始化OCR客户端
            if self.kimi_api_key:
                try:
                    self.processor.init_kimi_client()
                    QMessageBox.information(self, "成功", "API密钥设置成功！")
                except Exception as e:
                    QMessageBox.warning(self, "警告", f"初始化OCR客户端失败: {str(e)}")
            
            os.makedirs(self.temp_dir, exist_ok=True)
            
    def handle_function_click(self, category):
        """处理功能按钮点击"""
        # 显示功能区UI，隐藏截图区UI
        self.function_container.show()
        self.screenshot_container.hide()
        
        file_filters = []
        for ext in self.supported_formats[category]:
            if ext == '.pdf':
                file_filters.append("PDF文件 (*.pdf)")
            elif ext in ['.png', '.jpg', '.jpeg', '.bmp', '.gif']:
                file_filters.append("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)")
            elif ext in ['.docx', '.doc']:
                file_filters.append("Word文件 (*.docx *.doc)")
            elif ext in ['.xlsx', '.xls']:
                file_filters.append("Excel文件 (*.xlsx *.xls)")
            elif ext in ['.pptx', '.ppt']:
                file_filters.append("PPT文件 (*.pptx *.ppt)")
        
        file_filters.append("所有文件 (*.*)")
        filter_str = ";;".join(file_filters)
        
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            f"选择{category}文件",
            "",
            filter_str
        )
        
        if file_path:
            file_ext = os.path.splitext(file_path)[1].lower()
            if file_ext not in self.supported_formats[category]:
                QMessageBox.warning(self, "错误", f"不支持的文件格式: {file_ext}")
                return
                
            # 重置功能区显示信息
            self.reset_interface()
            
            # 更新文件信息
            self.current_operation = category
            self.file_path_label.setText(file_path)
            self.update_file_info(file_path)
            self.current_file_path = file_path
            
            # 更新转换类型下拉框
            self.conversion_combo.clear()
            self.conversion_combo.addItems(self.supported_operations[category])
            
            self.statusBar.showMessage(f"已选择文件: {file_path}")
            
    def reset_interface(self):
        """重置界面显示信息"""
        # 重置进度条
        self.progress_bar.setValue(0)
        
        # 重置结果显示
        self.result_label.setText("尚未开始转换")
        
        # 重置状态
        self.converted_file_path = None
        
        # 启用转换按钮
        self.convert_btn.setEnabled(True)
        
        # 清空转换类型下拉框
        self.conversion_combo.clear()
        
    def open_result_folder(self, path):
        """打开结果文件所在文件夹"""
        try:
            if os.path.exists(path):
                folder_path = os.path.dirname(path)
                if sys.platform == 'win32':
                    import subprocess
                    # 使用 cmd 命令打开文件夹并选中文件
                    folder_path = os.path.normpath(folder_path)
                    file_name = os.path.basename(path)
                    # 使用 cmd 命令打开文件夹
                    subprocess.run(['cmd', '/c', 'explorer', folder_path], shell=True)
                elif sys.platform == 'darwin':  # macOS
                    subprocess.run(['open', folder_path])
                else:  # Linux
                    subprocess.run(['xdg-open', folder_path])
        except Exception as e:
            QMessageBox.warning(self, "警告", f"无法打开文件夹：{str(e)}")
            
    def start_conversion(self):
        if not self.file_path_label.text() or self.file_path_label.text() == "未选择文件":
            self.statusBar.showMessage("请先选择要转换的文件", 3000)
            return
            
        if not self.current_operation or not self.conversion_combo.currentText():
            QMessageBox.warning(self, "警告", "请先选择要执行的操作类型")
            return
            
        try:
            # 使用设置中的临时文件夹
            os.makedirs(self.temp_dir, exist_ok=True)
            
            # 生成唯一的临时文件名
            operation = self.conversion_combo.currentText()
            base_name = os.path.splitext(os.path.basename(self.current_file_path))[0]
            # 替换非法字符
            safe_base_name = "".join(c for c in base_name if c.isalnum() or c in (' ', '-', '_')).strip()
            if not safe_base_name:  # 如果文件名全是非法字符，使用默认名称
                safe_base_name = "converted"
            timestamp = str(int(time.time()))
            
            # 根据操作类型确定输出文件扩展名
            if operation == "转图片":
                ext = ".png"
            elif operation == "转PDF":
                ext = ".pdf"
            elif operation == "转文本":
                ext = ".txt"
            elif operation == "转表格":
                ext = ".xlsx"
            elif operation == "转PPT":
                ext = ".pptx"
            elif operation == "转Word":
                ext = ".docx"
            elif operation == "转Excel":
                ext = ".xlsx"
            else:  # 去水印操作
                ext = os.path.splitext(self.current_file_path)[1]
                
            # 确保输出路径是绝对路径
            self.converted_file_path = os.path.abspath(os.path.join(self.temp_dir, f"{safe_base_name}_{timestamp}{ext}"))
            
            # 确保输出目录存在
            os.makedirs(os.path.dirname(self.converted_file_path), exist_ok=True)
            
            # 创建转换线程
            self.conversion_thread = ConversionThread(
                self.processor,
                self.current_file_path,
                self.converted_file_path,
                operation
            )
            
            # 连接信号
            self.conversion_thread.progress_updated.connect(self.update_progress)
            self.conversion_thread.conversion_finished.connect(self.conversion_finished)
            self.conversion_thread.error_occurred.connect(self.conversion_error)
            
            # 禁用按钮
            self.convert_btn.setEnabled(False)
            
            # 开始转换
            self.statusBar.showMessage("正在转换文件...")
            self.conversion_thread.start()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"准备转换时发生错误:\n{str(e)}")
            self.statusBar.showMessage("转换准备失败", 3000)
            
    def update_progress(self, value):
        self.progress_bar.setValue(value)
        
    def conversion_finished(self):
        """转换完成后的处理"""
        try:
            # 验证转换结果
            if not self.converted_file_path:
                raise Exception("未获取到转换后的文件路径")

            if isinstance(self.converted_file_path, list):
                # 处理多个文件的情况
                valid_files = []
                for path in self.converted_file_path:
                    # 使用绝对路径进行验证
                    abs_path = os.path.abspath(path)
                    if os.path.exists(abs_path) and os.path.getsize(abs_path) > 0:
                        valid_files.append(abs_path)
                
                if not valid_files:
                    # 再次检查temp目录
                    temp_dir = os.path.dirname(self.converted_file_path[0])
                    if os.path.exists(temp_dir):
                        for file in os.listdir(temp_dir):
                            if file.startswith(os.path.splitext(os.path.basename(self.converted_file_path[0]))[0]):
                                full_path = os.path.join(temp_dir, file)
                                if os.path.getsize(full_path) > 0:
                                    valid_files.append(full_path)
                
                if not valid_files:
                    raise Exception("未找到有效的转换文件")
                
                result_text = "转换完成，生成了以下文件：<br>"
                for i, path in enumerate(valid_files, 1):
                    file_url = "file:///" + path.replace("\\", "/")
                    result_text += f'<a href="{file_url}">文件 {i}: {os.path.basename(path)}</a><br>'
            else:
                # 处理单个文件的情况
                abs_path = os.path.abspath(self.converted_file_path)
                if not os.path.exists(abs_path):
                    # 检查temp目录
                    temp_dir = os.path.dirname(abs_path)
                    if os.path.exists(temp_dir):
                        for file in os.listdir(temp_dir):
                            if file.startswith(os.path.splitext(os.path.basename(abs_path))[0]):
                                abs_path = os.path.join(temp_dir, file)
                                break
                
                if not os.path.exists(abs_path):
                    raise Exception("转换后的文件不存在")
                    
                if os.path.getsize(abs_path) == 0:
                    raise Exception("转换后的文件为空")
                    
                file_url = "file:///" + abs_path.replace("\\", "/")
                result_text = f'转换完成，文件保存在：<br><a href="{file_url}">{os.path.basename(abs_path)}</a>'

            # 更新界面显示
            self.statusBar.showMessage("文件转换完成", 3000)
            self.progress_bar.setValue(100)
            self.result_label.setText(result_text)
            
        except Exception as e:
            error_msg = str(e)
            self.statusBar.showMessage("转换失败", 3000)
            self.result_label.setText(f"转换失败: {error_msg}")
            QMessageBox.critical(self, "错误", f"转换失败:\n{error_msg}")
            
        finally:
            # 启用转换按钮
            self.convert_btn.setEnabled(True)
            
    def conversion_error(self, error_msg):
        QMessageBox.critical(self, "错误", f"转换过程中发生错误:\n{error_msg}")
        self.statusBar.showMessage("转换失败", 3000)
        
        # 启用按钮
        self.convert_btn.setEnabled(True)
            
    def update_file_info(self, file_path):
        import os
        file_name = os.path.basename(file_path)
        file_size = os.path.getsize(file_path)
        file_ext = os.path.splitext(file_path)[1]
        
        info_text = f"""
文件名: {file_name}
文件大小: {file_size / 1024:.2f} KB
文件类型: {file_ext}
        """
        self.file_info_text.setText(info_text)

    def closeEvent(self, event):
        """程序关闭时清理临时文件"""
        try:
            if os.path.exists(self.temp_dir):
                shutil.rmtree(self.temp_dir)
        except Exception as e:
            print(f"清理临时文件失败: {str(e)}")
        event.accept()

    def show_screenshot(self):
        """显示截图界面"""
        # 隐藏功能区UI，显示截图区UI
        self.function_container.hide()
        self.screenshot_container.show()
        
        # 清空截图容器的现有内容
        for i in reversed(range(self.screenshot_layout.count())): 
            widget = self.screenshot_layout.itemAt(i).widget()
            if widget:
                widget.deleteLater()
        
        # 添加截图按钮
        button_container = QWidget()
        button_container.setStyleSheet("background-color: white;")
        button_layout = QVBoxLayout(button_container)
        button_layout.setContentsMargins(20, 20, 20, 20)  # 为按钮区域添加内边距
        
        # 添加截图按钮
        screenshot_btn = QPushButton("开始截图 (Alt + W)")
        screenshot_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                padding: 10px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 200px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        screenshot_btn.clicked.connect(self.take_screenshot)
        
        # 添加图片预览区域
        self.screenshot_preview = QLabel()
        self.screenshot_preview.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.screenshot_preview.setMinimumSize(400, 300)
        self.screenshot_preview.setStyleSheet("""
            QLabel {
                border: 2px solid #ddd;
                border-radius: 4px;
                background-color: #f9f9f9;
                margin: 10px;
            }
        """)
        
        # 添加OCR按钮
        ocr_btn = QPushButton("识别文字")
        ocr_btn.setStyleSheet("""
            QPushButton {
                background-color: #FF9800;
                color: white;
                padding: 10px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 200px;
            }
            QPushButton:hover {
                background-color: #f57c00;
            }
        """)
        ocr_btn.clicked.connect(self.ocr_screenshot)
        
        # 将按钮添加到按钮容器
        button_layout.addWidget(screenshot_btn)
        button_layout.addWidget(self.screenshot_preview)
        button_layout.addWidget(ocr_btn)
        button_layout.addStretch()
        
        # 将按钮容器添加到截图布局
        self.screenshot_layout.addWidget(button_container)

    def take_screenshot(self):
        """执行截图操作"""
        # 确保截图页面已初始化
        if not hasattr(self, 'screenshot_container') or not self.screenshot_container.isVisible():
            self.show_screenshot()
            
        # 隐藏主窗口
        self.hide()
        # 等待窗口完全隐藏
        QTimer.singleShot(200, self.start_screenshot)

    def start_screenshot(self):
        """开始截图"""
        screenshot_window = ScreenshotWindow()
        result = screenshot_window.exec()
        
        # 显示主窗口
        self.show()
        
        if result == QDialog.DialogCode.Accepted and screenshot_window.get_screenshot():
            self.screenshot_image = screenshot_window.get_screenshot()
            # 确保截图页面已初始化
            if not hasattr(self, 'screenshot_container') or not self.screenshot_container.isVisible():
                self.show_screenshot()
                
            # 自动保存到缓存目录
            cache_dir = os.path.join(os.path.expanduser("~"), ".file_converter", "temp")
            os.makedirs(cache_dir, exist_ok=True)
            timestamp = int(time.time())
            self.current_screenshot_path = os.path.join(cache_dir, f"screenshot_{timestamp}.png")
            self.screenshot_image.save(self.current_screenshot_path)
            
            # 更新预览
            preview_pixmap = self.screenshot_image.scaled(
                self.screenshot_preview.size(),
                Qt.AspectRatioMode.KeepAspectRatio,
                Qt.TransformationMode.SmoothTransformation
            )
            self.screenshot_preview.setPixmap(preview_pixmap)
            
            # 显示截图容器
            self.function_container.hide()
            self.screenshot_container.show()

    def ocr_screenshot(self):
        """对截图进行OCR识别"""
        if not hasattr(self, 'current_screenshot_path'):
            QMessageBox.warning(self, "提示", "请先进行截图")
            return
        
        try:
            # 创建进度对话框
            progress_dialog = QProgressDialog("正在识别文字...", None, 0, 0, self)
            progress_dialog.setWindowTitle("文字识别")
            progress_dialog.setWindowModality(Qt.WindowModality.WindowModal)
            progress_dialog.setMinimumDuration(0)
            progress_dialog.setCancelButton(None)
            progress_dialog.setAutoClose(True)
            progress_dialog.setStyleSheet("""
                QProgressDialog {
                    background-color: white;
                    border-radius: 5px;
                }
                QLabel {
                    color: #2c3e50;
                    font-size: 14px;
                    padding: 10px;
                }
                QProgressBar {
                    border: none;
                    border-radius: 4px;
                    text-align: center;
                    background-color: #ecf0f1;
                    height: 20px;
                }
                QProgressBar::chunk {
                    background-color: #3498db;
                    border-radius: 4px;
                }
            """)
            
            # 显示进度对话框
            progress_dialog.show()
            QApplication.processEvents()
            
            # 调用OCR功能
            output_path = self.processor.image_to_text(self.current_screenshot_path)
            
            # 关闭进度对话框
            progress_dialog.close()
            
            # 显示识别结果
            with open(output_path, "r", encoding="utf-8") as f:
                text = f.read()
                
            # 创建结果对话框
            dialog = QDialog(self)
            dialog.setWindowTitle("OCR识别结果")
            dialog.setMinimumWidth(400)
            dialog.setMinimumHeight(300)
            
            layout = QVBoxLayout()
            
            # 添加文本编辑框
            text_edit = QTextEdit()
            text_edit.setPlainText(text)
            text_edit.setReadOnly(True)
            
            # 添加复制按钮
            copy_btn = QPushButton("复制文本")
            copy_btn.setStyleSheet("""
                QPushButton {
                    background-color: #3498db;
                    color: white;
                    padding: 8px 15px;
                    border-radius: 4px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #2980b9;
                }
            """)
            copy_btn.clicked.connect(lambda: QApplication.clipboard().setText(text))
            
            layout.addWidget(text_edit)
            layout.addWidget(copy_btn)
            
            dialog.setLayout(layout)
            dialog.exec()
            
        except Exception as e:
            logging.error(f"OCR识别失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"OCR识别失败: {str(e)}")

    def handle_screenshot_click(self):
        """处理截图按钮点击"""
        # 取消其他功能按钮的选中状态
        for btn in self.function_buttons:
            btn.setChecked(False)
            
        # 显示截图界面
        self.show_screenshot()

class ScreenshotWindow(QDialog):
    def __init__(self):
        super().__init__()
        # 获取屏幕截图
        screen = QApplication.primaryScreen()
        if screen is None:
            QMessageBox.critical(None, "错误", "无法获取屏幕")
            self.reject()
            return
            
        self.screenshot = screen.grabWindow(0)
        if self.screenshot is None or self.screenshot.isNull():
            QMessageBox.critical(None, "错误", "无法获取屏幕截图")
            self.reject()
            return
            
        self.initUI()
        
    def initUI(self):
        # 设置窗口标志
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setStyleSheet('background-color: black;')
        self.setWindowState(Qt.WindowState.WindowFullScreen)
        self.setWindowOpacity(0.3)
        self.setCursor(Qt.CursorShape.CrossCursor)
        
        # 初始化变量
        self.begin = None
        self.end = None
        self.is_drawing = False
        self.final_screenshot = None
        
    def paintEvent(self, event):
        if not self.screenshot:
            return
            
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.screenshot)
        
        if self.begin and self.end:
            # 绘制半透明遮罩
            mask = QColor(0, 0, 0, 100)
            painter.fillRect(self.rect(), mask)
            
            # 计算选择区域
            x = min(self.begin.x(), self.end.x())
            y = min(self.begin.y(), self.end.y())
            width = abs(self.begin.x() - self.end.x())
            height = abs(self.begin.y() - self.end.y())
            
            # 清除选中区域的遮罩
            painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Clear)
            painter.fillRect(x, y, width, height, Qt.GlobalColor.transparent)
            
            # 绘制边框和尺寸信息
            painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)
            
            # 绘制边框
            pen = QPen(QColor('#2196F3'), 2)
            painter.setPen(pen)
            painter.drawRect(x, y, width, height)
            
            # 显示尺寸信息
            size_text = f'{width} x {height}'
            info_rect = QRect(x, y - 20, 70, 20)
            if y < 20:  # 如果太靠上，就显示在选区下方
                info_rect.moveTop(y + height)
            painter.fillRect(info_rect, QColor('#2196F3'))
            painter.setPen(Qt.GlobalColor.white)
            painter.drawText(info_rect, Qt.AlignmentFlag.AlignCenter, size_text)
    
    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_Escape:
            self.reject()
            
    def mousePressEvent(self, event):
        self.begin = event.pos()
        self.end = self.begin
        self.is_drawing = True
        self.update()
        
    def mouseMoveEvent(self, event):
        if self.is_drawing:
            self.end = event.pos()
            self.update()
            
    def mouseReleaseEvent(self, event):
        if self.begin and self.end:
            self.is_drawing = False
            self.capture_screenshot()
            
    def capture_screenshot(self):
        if not self.screenshot or not self.begin or not self.end:
            self.reject()
            return
            
        try:
            x = min(self.begin.x(), self.end.x())
            y = min(self.begin.y(), self.end.y())
            width = abs(self.begin.x() - self.end.x())
            height = abs(self.begin.y() - self.end.y())
            
            if width < 1 or height < 1:
                self.reject()
                return
                
            # 捕获选中区域的截图
            self.final_screenshot = self.screenshot.copy(x, y, width, height)
            self.accept()
            
        except Exception as e:
            QMessageBox.critical(None, "错误", f"截图失败: {str(e)}")
            self.reject()
            
    def get_screenshot(self):
        return self.final_screenshot

class SettingsDialog(QDialog):
    def __init__(self, current_temp_dir, file_processor, parent=None):
        super().__init__(parent)
        self.current_temp_dir = current_temp_dir
        self.file_processor = file_processor  # 保存FileProcessor实例
        self.setWindowTitle("设置")
        self.setup_ui()
        
    def setup_ui(self):
        layout = QVBoxLayout()
        
        # 临时目录设置
        temp_dir_group = QGroupBox("临时文件目录")
        temp_dir_layout = QHBoxLayout()
        self.temp_dir_edit = QLineEdit(self.current_temp_dir)
        self.temp_dir_edit.setReadOnly(True)
        browse_btn = QPushButton("浏览")
        browse_btn.clicked.connect(self.browse_temp_dir)
        temp_dir_layout.addWidget(self.temp_dir_edit)
        temp_dir_layout.addWidget(browse_btn)
        temp_dir_group.setLayout(temp_dir_layout)
        
        # KIMI API设置
        api_group = QGroupBox("KIMI API设置")
        api_layout = QVBoxLayout()
        
        # 从设置中加载API密钥
        settings = QSettings('FileConverter', 'Settings')
        saved_api_key = settings.value('kimi_api_key', '')
        
        # API密钥输入框
        api_key_layout = QHBoxLayout()
        api_key_label = QLabel("API密钥:")
        self.api_key_edit = QLineEdit(saved_api_key)
        self.api_key_edit.setEchoMode(QLineEdit.EchoMode.Password)  # 密码模式显示
        show_key_btn = QPushButton("显示")
        show_key_btn.setCheckable(True)
        show_key_btn.toggled.connect(lambda checked: self.api_key_edit.setEchoMode(
            QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password
        ))
        api_key_layout.addWidget(api_key_label)
        api_key_layout.addWidget(self.api_key_edit)
        api_key_layout.addWidget(show_key_btn)
        
        api_layout.addLayout(api_key_layout)
        api_group.setLayout(api_layout)
        
        # 添加到主布局
        layout.addWidget(temp_dir_group)
        layout.addWidget(api_group)
        
        # 确定和取消按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
        self.setLayout(layout)
        
    def browse_temp_dir(self):
        dir_path = QFileDialog.getExistingDirectory(
            self,
            "选择临时文件目录",
            self.temp_dir_edit.text()
        )
        if dir_path:
            self.temp_dir_edit.setText(dir_path)
            
    def get_temp_dir(self):
        return self.temp_dir_edit.text()
        
    def get_api_key(self):
        return self.api_key_edit.text()
        
    def accept(self):
        # 获取并保存API密钥
        api_key = self.api_key_edit.text().strip()
        if api_key:
            self.file_processor.set_api_key(api_key)
            
            # 保存API密钥到设置
            settings = QSettings('FileConverter', 'Settings')
            settings.setValue('kimi_api_key', api_key)
        super().accept()

def main():
    app = QApplication(sys.argv)
    window = FileConverterApp()
    window.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main() 